import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/control_room/lake_recommend_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/toolkit/widgets/report_focus_curtain.dart';

part 'lake_recommend_production.page.dart';

/// 湖泊详情页面
@PagePath('/lake-recommend/:lakeId')
class LakeRecommendProduction extends StatefulWidget {
  final String lakeId;

  const LakeRecommendProduction({super.key, required this.lakeId});

  @pageRouteQuery
  static RouteQuery query({required String lakeId}) =>
      _$LakeRecommendProductionQuery().call(lakeId: lakeId);

  @override
  State<LakeRecommendProduction> createState() =>
      _LakeRecommendProductionState();
}

class _LakeRecommendProductionState extends State<LakeRecommendProduction> {
  late LakeRecommendRoom _lakeRecommendRoom;
  String? _selectedLakeId;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _lakeRecommendRoom = GlobalStateProvider.lakeRecommendRoomOf(context);
    _selectedLakeId = widget.lakeId;
  }

  /// 切换湖泊
  void _switchLake(String lakeId) {
    setState(() {
      _selectedLakeId = lakeId;
    });
  }

  /// 处理举报
  void _handleReport() {
    if (_selectedLakeId == null) return;

    ReportAccusation.raise(
      context,
      targetId: _selectedLakeId!,
      targetType: 'lake',
      onReportSubmitted: (reason) {
        _lakeRecommendRoom.removeLakeRecommend(_selectedLakeId!);
        Navigator.of(context).pop();
      },
    );
  }

  /// 获取当前选中的湖泊
  _LakeData? _getCurrentLake() {
    if (_selectedLakeId == null) return null;
    final lake = _lakeRecommendRoom.fetchLakeRecommendById(_selectedLakeId!);
    if (lake == null) return null;
    return _LakeData(
      id: lake.id,
      title: lake.title,
      location: lake.location,
      description: lake.description,
      imageUrl: lake.imageUrl,
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),

          Expanded(
            child: Center(
              child: Text('Famous Lake')
                  .fontSize(24.sp)
                  .textColor(ColorPalette.black)
                  .carterOne(weight: FontWeight.w400),
            ),
          ),

          // 举报按钮
          GestureDetector(
            onTap: _handleReport,
            child: Container(
              width: 40.w,
              height: 40.w,
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Image.asset(
                AssetManifest.report2,
                width: 24.w,
                height: 24.w,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建湖泊图片
  Widget _buildLakeImage() {
    final lake = _getCurrentLake();
    if (lake == null) return SizedBox.shrink();

    return AnimatedSwitcher(
      duration: Duration(milliseconds: 300),
      transitionBuilder: (child, animation) {
        return FadeTransition(opacity: animation, child: child);
      },
      child: AspectRatio(
        key: ValueKey(lake.id),
        aspectRatio: 358 / 250,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            image: DecorationImage(
              image: AssetImage(lake.imageUrl),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建湖泊列表
  Widget _buildLakeList() {
    final lakes = _lakeRecommendRoom.fetchAllLakeRecommends();
    if (lakes.isEmpty) return SizedBox.shrink();

    return Container(
      margin: EdgeInsets.only(top: 16.h),
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children:
            lakes.asMap().entries.map((entry) {
              final index = entry.key;
              final lake = entry.value;
              final isSelected = _selectedLakeId == lake.id;
              return Expanded(
                child: Padding(
                  padding: EdgeInsets.only(
                    right: index < lakes.length - 1 ? 12.w : 0,
                  ),
                  child: GestureDetector(
                    onTap: () => _switchLake(lake.id),
                    child: Stack(
                      children: [
                        AnimatedContainer(
                          duration: Duration(milliseconds: 300),
                          curve: Curves.easeInOut,
                          padding: EdgeInsets.all(8.w),
                          decoration: BoxDecoration(
                            color: ColorPalette.white,
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                          child: Row(
                            children: [
                              // 左侧图片
                              Container(
                                width: 43.w,
                                height: 43.w,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8.r),
                                  image: DecorationImage(
                                    image: AssetImage(lake.imageUrl),
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                              8.w.widthBox,
                              // 右侧列：标题和地点
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                          lake.title,
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                        )
                                        .fontSize(12.sp)
                                        .textColor(ColorPalette.black)
                                        .arimo(weight: FontWeight.w700),
                                    2.h.heightBox,
                                    Text(
                                          lake.location,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        )
                                        .fontSize(10.sp)
                                        .textColor(const Color(0xFF666666))
                                        .arimo(weight: FontWeight.w400),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        // 未选中时的灰色蒙层
                        Positioned.fill(
                          child: AnimatedOpacity(
                            duration: Duration(milliseconds: 300),
                            opacity: isSelected ? 0.0 : 0.5,
                            child: Container(
                              decoration: BoxDecoration(
                                color: ColorPalette.black,
                                borderRadius: BorderRadius.circular(8.r),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            }).toList(),
      ),
    );
  }

  /// 构建湖泊详情信息
  Widget _buildLakeDetails() {
    final lake = _getCurrentLake();
    if (lake == null) return SizedBox.shrink();

    return AnimatedSwitcher(
      duration: Duration(milliseconds: 300),
      transitionBuilder: (child, animation) {
        return FadeTransition(opacity: animation, child: child);
      },
      child: Container(
        key: ValueKey(lake.id),
        margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          color: ColorPalette.white,
          borderRadius: BorderRadius.circular(16.r),
          boxShadow: [
            BoxShadow(
              color: ColorPalette.black.withValues(alpha: 0.05),
              blurRadius: 10,
              offset: Offset(0, 2.h),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            Text(lake.title)
                .fontSize(24.sp)
                .textColor(ColorPalette.black)
                .carterOne(weight: FontWeight.w400),
            8.h.heightBox,
            // 描述
            Text(
              lake.description,
              style: TextStyle(
                fontSize: 14.sp,
                color: ColorPalette.black,
                height: 1.6,
              ),
            ).arimo(weight: FontWeight.w400),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 固定标题栏
              _buildTopBar(),
              // 可滚动内容
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // 湖泊图片
                      _buildLakeImage(),
                      // 湖泊列表
                      _buildLakeList(),
                      // 湖泊详情
                      _buildLakeDetails(),
                      32.h.heightBox,
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// 湖泊数据模型
class _LakeData {
  final String id;
  final String title;
  final String location;
  final String description;
  final String imageUrl;

  _LakeData({
    required this.id,
    required this.title,
    required this.location,
    required this.description,
    required this.imageUrl,
  });
}
